package com.children.growth.controller;

import com.children.growth.common.JwtUtil;
import com.children.growth.common.Result;
import com.children.growth.entity.User;
import com.children.growth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 * 
 * @author children
 * @since 1.0.0
 */
 @RestController
 @RequestMapping("/user")
 @CrossOrigin(origins = "*", maxAge = 3600)
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<Map<String, Object>> register(@RequestBody User user) {
        try {
            boolean success = userService.register(user);
            if (success) {
                Map<String, Object> data = new HashMap<>();
                data.put("userId", user.getId());
                data.put("username", user.getUsername());
                return Result.success("注册成功", data);
            } else {
                return Result.error("注册失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginForm) {
        try {
            String username = loginForm.get("username");
            String password = loginForm.get("password");

            if (username == null || password == null) {
                return Result.badRequest("用户名和密码不能为空");
            }

            String token = userService.login(username, password);
            User user = userService.getUserByUsername(username);

            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", user);

            return Result.success("登录成功", data);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo(HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            if (token == null) {
                return Result.unauthorized("未提供认证token");
            }

            String username = jwtUtil.getUsernameFromToken(token);
            User user = userService.getUserByUsername(username);

            if (user == null) {
                return Result.notFound("用户不存在");
            }

            // 清除敏感信息
            user.setPassword(null);

            return Result.success(user);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/info")
    public Result<String> updateUserInfo(@RequestBody User user, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            if (token == null) {
                return Result.unauthorized("未提供认证token");
            }

            Long userId = jwtUtil.getUserIdFromToken(token);
            user.setId(userId);

            boolean success = userService.updateUserInfo(user);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PostMapping("/change-password")
    public Result<String> changePassword(@RequestBody Map<String, String> passwordForm, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            if (token == null) {
                return Result.unauthorized("未提供认证token");
            }

            Long userId = jwtUtil.getUserIdFromToken(token);
            String oldPassword = passwordForm.get("oldPassword");
            String newPassword = passwordForm.get("newPassword");

            if (oldPassword == null || newPassword == null) {
                return Result.badRequest("原密码和新密码不能为空");
            }

            boolean success = userService.changePassword(userId, oldPassword, newPassword);
            if (success) {
                return Result.success("密码修改成功");
            } else {
                return Result.error("密码修改失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 检查用户名是否存在
     */
    @GetMapping("/check-username")
    public Result<Map<String, Boolean>> checkUsername(@RequestParam String username) {
        try {
            boolean exists = userService.isUsernameExists(username);
            Map<String, Boolean> data = new HashMap<>();
            data.put("exists", exists);
            return Result.success(data);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 检查邮箱是否存在
     */
    @GetMapping("/check-email")
    public Result<Map<String, Boolean>> checkEmail(@RequestParam String email) {
        try {
            boolean exists = userService.isEmailExists(email);
            Map<String, Boolean> data = new HashMap<>();
            data.put("exists", exists);
            return Result.success(data);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 检查手机号是否存在
     */
    @GetMapping("/check-phone")
    public Result<Map<String, Boolean>> checkPhone(@RequestParam String phone) {
        try {
            boolean exists = userService.isPhoneExists(phone);
            Map<String, Boolean> data = new HashMap<>();
            data.put("exists", exists);
            return Result.success(data);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
} 